package app.fugema.shop.helper;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.base.common.BuildConfig;
import com.base.common.app.BaseConstant;
import com.base.common.model.bean.WeChatPayResponse;
import com.base.common.utils.LogUtil;
import com.base.common.utils.MD5AndSHA;
import com.base.common.utils.SPUtils;
import com.base.common.utils.UIUtils;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;


public class WeChatHelper {

    public static void init(Context context) {
        regToWx(context);
    }

    // IWXAPI 是第三方app和微信通信的openApi接口
    private static IWXAPI api;

    private static void regToWx(Context context) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, AppConstants.AppKey.WxAppId, true);
        // 将应用的appId注册到微信
        api.registerApp(AppConstants.AppKey.WxAppId);

    }

    public static void login() {
        if (api.isWXAppInstalled()) {
            // send oauth request
            SendAuth.Req req = new SendAuth.Req();
            req.scope = AppConstants.REQ_SCOPE;
            req.state = AppConstants.REQ_STATE;
            api.sendReq(req);
        } else {
            UIUtils.showToastSafes("没有安装微信");
        }
    }

    /**
     * @param payInfo
     * @param isSign  是否需要自已签名
     */
    public static void pay(WeChatPayResponse.PayInfoBean payInfo, boolean isSign) {
        PayReq req = new PayReq();
        //req.appId = "wxf8b4f85f3a794e77";  // appId
        req.appId = payInfo.getAppid();
        req.partnerId = payInfo.getPartnerid();
        req.prepayId = payInfo.getPrepayid();
        req.nonceStr = payInfo.getNoncestr();
        req.timeStamp = payInfo.getTimestamp();
        req.packageValue = payInfo.getPackageX();
        if (isSign) {
            req.sign = getWxSignValue(payInfo);
        } else {
            req.sign = payInfo.getSign();
        }
        api.sendReq(req);
    }

    /**
     * 微信 二次签名方法
     *
     * @param data
     * @return
     */
    private static String getWxSignValue(WeChatPayResponse.PayInfoBean data) {
        SortedMap<String, Object> parameters = new TreeMap<>();
        // 把参数的值传进去SortedMap集合里面
        parameters.put("appid", data.getAppid());
        parameters.put("noncestr", data.getNoncestr());
        parameters.put("package", "Sign=WXPay");
        parameters.put("partnerid", data.getPartnerid());
        parameters.put("prepayid", data.getPrepayid());
        parameters.put("timestamp", data.getTimestamp());

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        String key = "11111111111111111111111111111111";
        sb.append("key=" + key); //KEY是商户秘钥
        String sign = MD5AndSHA.md5Encode(sb.toString()).toUpperCase();
        String sha256 = MD5AndSHA.SHA256Encode(sb.toString(), key);

        LogUtil.d("encode", "start------------");
        LogUtil.d("encode", "str=" + sb.toString());
        LogUtil.d("encode", "sign=" + sign);
        LogUtil.d("encode", "sha256=" + sha256);
        LogUtil.d("encode", "end------------");
        return sha256;
    }


    public static void handResp(Intent intent, IWXAPIEventHandler handler) {
        api.handleIntent(intent, handler);
    }

    //返回消息处理
    public static String handResp2Str(BaseResp baseResp) {
        String resp = null;
        if (baseResp.errCode == 0) {
            //同意
        } else if (baseResp.errCode == BaseResp.ErrCode.ERR_AUTH_DENIED) {
            //拒绝
            resp = UIUtils.getString(R.string.wechat_login_reject);
        } else if (baseResp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
            //取消
            resp = UIUtils.getString(R.string.wechat_login_cancel);
        } else if (baseResp.errCode == BaseResp.ErrCode.ERR_SENT_FAILED) {
            //失败
            resp = UIUtils.getString(R.string.wechat_login_fail);
        }

        return resp;
    }


    //分享小程序类型消息至会话
    public static void shareToSomeone(byte[] bitmap, String sharePath, String title) {
        shareToSomeone(bitmap, sharePath, title, "");
    }

    //发起分享的App与小程序属于同一微信开放平台帐号。
    //支持分享小程序类型消息至会话，暂不支持分享至朋友圈
    public static void shareToSomeone(byte[] bitmap, String sharePath, String title, String description) {
        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        // 兼容低版本的网页链接
        miniProgramObj.webpageUrl = "https://www.baidu.com";
        //// 正式版:0，测试版:1，体验版:2
        miniProgramObj.miniprogramType = BuildConfig.DEBUG ? WXMiniProgramObject.MINIPROGRAM_TYPE_TEST : WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;
        // 小程序原始id
        miniProgramObj.userName = AppConstants.WECHAT_SHARE_ID;

        //小程序页面路径；
        if (!TextUtils.isEmpty(sharePath)) {
            miniProgramObj.path = sharePath;
        }

        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        // 小程序消息title
        msg.title = title;
        // 小程序消息desc
        msg.description = description;
        // 小程序消息封面图片，小于128k
        msg.thumbData = bitmap;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = buildTransaction("miniProgram");
        req.message = msg;


        // 目前只支持会话
        // 分享到对话: SendMessageToWX.Req.WXSceneSession
        //分享到朋友圈: SendMessageToWX.Req.WXSceneTimeline
        //分享到收藏: SendMessageToWX.Req.WXSceneFavorite
        req.scene = SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }


    public static void launchToWithDraw() {
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        // 填小程序原始id
        req.userName = AppConstants.WECHAT_SHARE_ID;
        //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        req.path = "pages/User/Withdraw/Index?token=" + SPUtils.getString(BaseConstant.GATEWAY_TOKEN, "") + "&isFromApp=1";
        // 可选打开 开发版，体验版和正式版
        req.miniprogramType = BuildConfig.DEBUG ? WXMiniProgramObject.MINIPROGRAM_TYPE_TEST : WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;
        api.sendReq(req);
    }


    //分享图片到朋友圈
    public static void shareToCircle(Bitmap bitmap) {
        WXImageObject wxImageObject = new WXImageObject(bitmap);
        // 兼容低版本的网页链接
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = buildTransaction("miniProgram");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;  //朋友圈
        api.sendReq(req);
    }

    //分享图片到朋友
    public static void shareToWX(Bitmap bitmap) {
        WXImageObject wxImageObject = new WXImageObject(bitmap);
        // 兼容低版本的网页链接
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = buildTransaction("miniProgram");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;//会话
        api.sendReq(req);
    }


}
